package com.xiaohudie.util;

/**
 * @Author xiao hu die
 * @Date 2022/3/6 13:56
 * @Version 1.0
 */

import cn.hutool.json.JSONUtil;
import com.xiaohudie.pojo.RedisDate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**缓存工具类*/
@Component
@Slf4j
public class CacheClient {
 private final StringRedisTemplate stringRedisTemplate ;
 public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object object, Long time, TimeUnit timeUnit){
     /**将object转为String
      * 这样才能被redis接收*/
        String s = JSONUtil.toJsonStr(object);
        stringRedisTemplate.opsForValue().set(key,s,time,timeUnit);
    }
    /**逻辑过期方法*/
    public void setWithLogicalExpire(String key, Object object, Long time, TimeUnit timeUnit){
        /**将object转为String
         * 这样才能被redis接收*/
        RedisDate redisDate = new RedisDate();
        redisDate.setData(object);
        redisDate.setLocalDateTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        String s = JSONUtil.toJsonStr(redisDate);
        stringRedisTemplate.opsForValue().set(key,s);
    }
}
